package com.yukino.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.yukino.pojo.requestBody.LoginBody;
import com.yukino.pojo.serviceResult.LoginUser;
import com.yukino.service.UserService;
import com.yukino.util.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param loginBody 异步提交的请求信息
     * @return
     */
    @PostMapping("/user/login")
    public AjaxJson login(@RequestBody LoginBody loginBody) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();

        LoginUser login = userService.login(username, password);
        if (login.getCode() == 0) {
            StpUtil.setLoginId(username);

            return AjaxJson.getSuccess("登录成功", StpUtil.getTokenInfo());
        } else {
            return AjaxJson.getError("用户名或密码错误");
        }
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/user/logout")
    public AjaxJson logout(){
        StpUtil.logout();
        return AjaxJson.getSuccess("登出成功");
    }

}
